package logic

import (
	"CampusCloudAid/dao/mysql"
	"CampusCloudAid/models"
	"CampusCloudAid/pkg/jwt"
	"CampusCloudAid/pkg/snowflake"
	"fmt"
	"strings"
	"time"

	"go.uber.org/zap"
)

// Login 登录逻辑判断
func Login(p *models.ParamLogin) (u *models.Users, err error) {
	//判断传入的参数是邮箱还是手机号 有没有‘@’
	if strings.Contains(p.PhoneOrEmail, "@") {
		u, err = mysql.GetPhoneOrEmail("email", p.PhoneOrEmail)
		if err != nil {
			return nil, err
		}
	} else {
		//手机号
		u, err = mysql.GetPhoneOrEmail("phone", p.PhoneOrEmail)
		if err != nil {
			return nil, err
		}
	}

	if err = mysql.Login(p.Password, u.Password); err != nil {
		return nil, err
	}
	//判断是否是第一次登录
	if u.LoginTime == "" {
		u.FirstLogin = "新用户第一次登录"
	}
	/*if !u.LoginTime.Valid {
		u.FirstLogin = "新用户第一次登录"
	}*/
	//更新用户的登录时间
	if err := mysql.UpdateLoginTime(u); err != nil {
		return nil, err
	}
	// 生成token
	tokenString, _ := jwt.GenerateTokenByAdmin(u)
	u.Token = tokenString
	return u, nil
}

// Register 注册逻辑
func Register(p *models.ParamSignUp) (err error) {
	//判断手机号是否存在
	if _, err = mysql.CheckUserPhoneExist(p.Phone); err != nil {
		return
	}
	if _, err = mysql.CheckUserExist(p.Nickname); err != nil {
		return
	}
	//雪花算法生成uid
	uid, _ := snowflake.GetID()
	id, _ := snowflake.GetID()
	account := &models.AccountBalance{
		Id:     int64(id),
		UserId: int64(uid),
	}
	user := &models.Users{
		Uid:          int64(uid),
		Nickname:     p.Nickname,
		Gender:       p.Gender,
		Password:     p.Password,
		Phone:        p.Phone,
		RegisterTime: time.Now().Format("2006-01-02 15:04:05"),
		UpdateTime:   time.Now().Format("2006-01-02 15:04:05"),
		LoginTime:    "",
	}

	if err = mysql.Register(user); err != nil {
		return err
	}
	if err = mysql.RegisterAccount(account); err != nil {
		return err
	}
	return
}

// GetUserInfoByID 通过用户id查询用户个人信息
func GetUserInfoByID(userID int64) (*models.Users, error) {
	user, err := mysql.GetUserInfoByID(userID)
	if err != nil {
		return nil, err
	}
	return user, nil
}

// UpdateUserInfo 更新用户信息
func UpdateUserInfo(userId int64, fields map[string]interface{}) error {
	validFields := map[string]bool{
		"phone":    true,
		"nickname": true,
		"gender":   true,
		"email":    true,
		"campus":   true,
		"bio":      true,
	}

	for key, value := range fields {
		if !validFields[key] {
			zap.L().Error("无法修改的字段")
			return fmt.Errorf("无法修改字段：%s", key)
		}

		// 手机号验证
		if key == "phone" {
			phone, _ := value.(string)
			//if !ok || len(phone) != 11 {
			//	zap.L().Error("手机号格式不正确")
			//	return fmt.Errorf("手机格式不正确：%v", value)
			//}
			if _, err := mysql.CheckUserPhoneExist(phone); err != nil {
				zap.L().Error("手机号已存在")
				return err
			}
		}

		// 邮箱验证
		if key == "email" {
			email, _ := value.(string)
			//if !ok || !strings.Contains(email, "@") {
			//	zap.L().Error("邮箱格式不正确")
			//	return fmt.Errorf("邮箱格式不正确：%v", value)
			//}
			if _, err := mysql.CheckUserEmailExist(email); err != nil {
				zap.L().Error("邮箱已存在")
				return err
			}
		}
	}
	err := mysql.UpdateUserInfoByID(userId, fields)
	if err != nil {
		return err
	}
	return nil
}

// ReceivedTasksByUserId  查询用户接收的单子
func ReceivedTasksByUserId(userId int64) ([]*models.TaskWithUsername, error) {
	tasks, err := mysql.ReceivedTasksByID(userId)
	if err != nil {
		return nil, err
	}

	return tasks, nil
}

// CreatedTasksByUserId  查询用户发起的单子
func CreatedTasksByUserId(userId int64) ([]*models.TaskWithUsername, error) {
	tasks, err := mysql.CreatedTasksByID(userId)
	if err != nil {
		return nil, err
	}

	return tasks, nil
}

// UpdateUserAvatar 更新用户头像
func UpdateUserAvatar(userID int64, avatar string) error {
	err := mysql.UpdateUserAvatar(userID, avatar)
	if err != nil {
		return err
	}
	return nil
}

//func GetUserNicknameByPublishID(publishID uint) (string, error) {
//	nickname, err := mysql.GetUserNicknameByPublishID(publishID)
//	if err != nil {
//		return "", err
//	}
//	return nickname, err
//}
